package org.jash.ting13.user

import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.flow.consumeAsFlow
import kotlinx.coroutines.launch
import org.jash.ting13.net.APIService
import org.jash.utils.mvi.BaseViewModel
import org.jash.utils.net.service

class LoginViewModel:BaseViewModel<LoginIntent, LoginState>() {
    private val service:APIService by lazy { service() }
    init {
        viewModelScope.launch {
            intent.consumeAsFlow().collect {
                when(it) {
                    is LoginIntent.Verify -> getVerify()
                    is LoginIntent.User -> login(it)
                }
            }
        }

    }
    private suspend fun getVerify() {
        val bitmap = service.getVerify()
        state.postValue(LoginState.Verify(bitmap))
    }
    private suspend fun login(user:LoginIntent.User) {
        val s = try {
            val result = service.login(user.username, user.password, user.verify)
            when(result.state) {
                "success" -> LoginState.Success(result.message)
                else -> LoginState.Failure(result.message)
            }
        } catch (e: Exception) {
            LoginState.Failure(e.message ?: "")
        }
        state.postValue(s)

    }
}